import RootStore from '@xkit-yx/im-store'
import { NimKitCore } from '@xkit-yx/core-kit/dist/uniapp-nim-core'
import { getMsgContentTipByType } from '@/pages/im/utils/msg'
import { getUniPlatform } from '@/pages/im/utils'
import { beOver } from '@/utils/http'
// #ifdef APP-PLUS
const nimPushPlugin = uni.requireNativePlugin('NIMUniPlugin-PluginModule')
// #endif
let nim
interface state {
  loadText: object
  appkey: string
  // nim: any;
  browser: any
}
const state: state = {
  loadText: {
    loadmore: '上拉加载更多',
    loading: '数据加载中...',
    nomore: '已展示全部',
    error: '加载失败，点击重新加载'
  },
  // 网易云信appkey
  //   appkey: 'd65f42cef28af7a9d9c27a8f6bebcdb1',
  appkey: '9bca601324c6cbe39bbc16003a72fc2d',
  // nim: null,
  browser: null
}

const mutations = {
  SET_BROWSER(state, payload) {
    // console.log(payload)
    state.browser = payload
  },
  IM_INIT(state, payload) {
    // const isWeixinApp = getUniPlatform() === 'mp-weixin';
    // @ts-ignore
    const eventList = [
      'logined',
      'multiPortLogin',
      'kicked',
      'willReconnect',
      'disconnect',
      'msg',
      'syncdone',
      'proxyMsg',
      'syncRoamingMsgs',
      'syncOfflineMsgs',
      'syncMyNameCard',
      'syncdone',
      'sessions',
      'updateMyNameCard',
      'updateBlackList',
      'updateMuteList',
      'sysMsg',
      'syncSysMsgs',
      'syncFriend',
      'friends',
      'users',
      'updateSystemMessages',
      'sysMsgUnread',
      'pushEvents',
      'teamMsgReceipts',
      'updateSession',
      'teams',
      'createTeam',
      'updateTeamMember',
      'updateTeam',
      'addTeamMembers',
      'updateTeamManagers',
      'transferTeam',
      'removeTeamMembers',
      'dismissTeam',
      'updateTeamMembersMute'
    ]

    nim = new NimKitCore({
      initOptions: {
        appkey: payload.appId, // 请填写你的appkey
        account: payload.imAccid, // 请填写你的account
        token: payload.imToken, // 请填写你的token
        // lbsUrls: isWeixinApp ? ['https://lbs.netease.im/lbs/wxwebconf.jsp'] : ['https://lbs.netease.im/lbs/webconf.jsp'],
        lbsUrls: ['https://lbs.netease.im/lbs/webconf.jsp'],
        linkUrl: 'weblink.netease.im',
        needReconnect: true,
        onsysmsg: eventList
        /**
         * 使用固定设备ID，
         */
        // isFixedDeviceId: true,
        // "reconnectionAttempts": 5,
        // debugLevel: 'debug'
      },
      platform: 'UniApp'
    })

    uni.$UIKitNIM = nim

    // @ts-ignore
    uni.$UIKitStore = new RootStore(nim, {
      addFriendNeedVerify: false,
      teamBeInviteMode: 'noVerify',
      teamJoinMode: 'noVerify',
      teamUpdateExtMode: 'all',
      teamUpdateTeamMode: 'all',
      teamInviteMode: 'all',
      sendMsgBefore: async (options, type) => {
        const pushContent = getMsgContentTipByType({ body: options.body, type })

        // 如果是 at 消息，需要走离线强推
        const { forcePushIDsList, needForcePush } = options.ext?.yxAitMsg
          ? // @ts-ignore
            store.msgStore._formatExtAitToPushInfo(options.ext?.yxAitMsg, options.body)
          : { forcePushIDsList: '[]', needForcePush: false }

        // console.log('forcePushIDsList: ', forcePushIDsList)

        // 不同产商的推送消息体
        const { scene, to } = options
        const pushPayload = JSON.stringify({
          // oppo
          oppoField: {
            click_action_type: 4, // 参考 oppo 官网
            click_action_activity: '', // 各端不一样 TODO
            action_parameters: { sessionId: scene, sessionType: to } // 自定义
          },

          // vivo
          vivoField: {
            pushMode: 0 //推送模式 0：正式推送；1：测试推送，不填默认为0
          },

          // huawei
          hwField: {
            click_action: {
              type: 1,
              action: '' // 各端不一样 TODO
            },
            androidConfig: {
              category: 'IM',
              data: JSON.stringify({ sessionId: to, sessionType: scene })
            }
          },

          // 通用
          sessionId: to,
          sessionType: scene
        })

        const pushInfo = {
          needPush: true,
          needPushBadge: true,
          pushPayload: '{}',
          pushContent,
          needForcePush,
          forcePushIDsList,
          forcePushContent: pushContent
        }
        return { ...options, pushInfo }
      }
    })

    // console.log(nim);

    eventList.forEach((key: any) => {
      nim.on(key, (res) => {
        console.log(key, res)
        if (key === 'syncFriend') {
          const data = res ? JSON.parse(JSON.stringify(res)) : res
          if (data && data.type === 'deleteFriend') {
            uni.$UIKitStore.sessionStore.deleteSessionActive('p2p-' + res.account)
          }
        } else if (key === 'multiPortLogin') {
          const data = res ? JSON.parse(JSON.stringify(res)) : res
          nim.nim.kick(
            data.map((v) => {
              return v.deviceId
            })
          )
        } else if (key === 'kicked') {
          uni.showModal({
            title: '提示',
            content: '您当前的登陆信息已过期，点击确定重新登陆',
            showCancel: false,
            success: (res) => {
              beOver()
              uni.reLaunch({
                url: '/pages/login/index'
              })
            }
          })
        }
      })
    })

    // #ifdef APP-PLUS
    // 注册推送
    nim.getNIM().offlinePush.setOfflinePushConfig({
      plugin: nimPushPlugin,
      authConfig: {
        // xiaomi
        xmAppId: '',
        xmAppKey: '',
        xmCertificateName: 'KIT_UNIAPP_MI_PUSH',

        // huawei
        hwAppId: '',
        hwCertificateName: 'KIT_UNIAPP_HW_PUSH',

        // oppo
        oppoAppId: '',
        oppoAppKey: '',
        oppoAppSecret: '',
        oppoCertificateName: 'KIT_UNIAPP_OPPO_PUSH',

        /**
         * 注意vivo的appid和appkey需要同时在此处，以及manifest.json(即插件参数配置)中配置
         */
        vivoAppId: '',
        vivoAppKey: '',
        vivoCertificateName: 'KIT_UNIAPP_VIVO_PUSH',

        // fcm
        fcmCertificateName: 'KIT_UNIAPP_FCM_PUSH',

        // meizu
        mzAppId: '',
        mzAppKey: '',
        mzCertificateName: 'KIT_UNIAPP_MZ_PUSH',

        // iOS
        apnsCertificateName: 'dis_im_uniapp'
      }
    })
    // #endif

    nim.connect()
  }
}

const actions = {
  async IM_CONNECT({ commit, rootState }, payload) {
    if (nim) {
      const res = await nim.connect()
      //   console.log('im已成功连接', res)
    } else {
      console.error('im未初始化，执行初始化')
      commit('IM_INIT', payload)
    }
  },
  async IM_DISCONNECT({ commit, rootState }, payload) {
    if (nim) {
      const res = await nim.disconnect()
      //   console.log('im已断开连接')
      return res
    } else {
      console.error('im未初始化')
      return Promise.reject()
    }
  },
  async IM_DESTROY({ commit, rootState }, payload) {
    if (nim) {
      const res = await nim.destroy()
      nim = null
      //   console.log('im实例已销毁')
    } else {
      console.error('im未初始化, 无需销毁')
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
